package com.example.springboot4.system.security.handle;

import com.alibaba.fastjson2.JSON;
import com.example.springboot4.system.model.LoginUser;
import com.example.springboot4.system.model.Result;
import com.example.springboot4.system.security.jwt.JwtTokenUtils;
import com.example.springboot4.system.util.ServletUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import java.util.Objects;

/**
 * 登出处理类
 *
 * @author 宋义州
 * @since 2024/1/13 17:43
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    @Resource
    private JwtTokenUtils jwtTokenUtils;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        LoginUser loginUser = jwtTokenUtils.getLoginUser(request);
        if (Objects.nonNull(loginUser)) {
            // 删除用户缓存记录
            jwtTokenUtils.delLoginUser(loginUser.getToken());
        }
        ServletUtils.renderString(response, JSON.toJSONString(Result.success("登出成功！")));
    }

}
